﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TinyPMS_Jerusalem.Models.DBModel;
using TinyPMS_Jerusalem.Models;

namespace TinyPMS_Jerusalem.Controllers
{
    public class PropertyAdminController : Controller
    {
        Models.Interface.IPropertyAdminRepository adminRepository = new Models.PropertyAdminDBModel(new DBModelDataContext());
        List<SelectListItem> availableList;
        List<SelectListItem> categoryList;
        // GET: /Property/Create
        [Authorize(Roles = "Admin")]
        public ActionResult Create()
        {
            adminRepository.CreateViewDataForDropLists(out categoryList, out availableList);
            ViewData["Available"] = availableList;
            ViewData["Category"] = categoryList;
            return View();
        }

        //
        // POST: /Property/Create
        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                Property property = new Property();
                UpdateModel<Property>(property);
                if (adminRepository.IsExist(property.ID))          //验证物品ID是否存在
                {
                    ViewData.ModelState.AddModelError("ID", "物品ID已存在，请重新输入");         //返回对应的错误信息
                    return View();
                }
                adminRepository.Add(property);
                adminRepository.Save();
                return RedirectToAction("List", "Property", new { id = property.ID });
            }
            catch
            {
                adminRepository.CreateViewDataForDropLists(out categoryList, out availableList);
                ViewData["Available"] = availableList;       //IMPORTANT:此处Key的值应与对应的属性的名称相同，否者返回时用UpdateModel将无法更新。
                ViewData["Category"] = categoryList;       //IMPORTANT:此处Key的值应与对应的属性的名称相同，否者返回时用UpdateModel将无法更新。
                return View();
            }
        }


        // GET: /Property/Edit/5
        [Authorize(Roles = "Admin")]
        public ActionResult Edit(string id)
        {
            Property property = adminRepository.GetElementByID(id);
            if (property == null)
                throw new ArgumentException("未找到对应的物品");
            adminRepository.CreateViewDataForDropLists(out categoryList, out availableList);
            ViewData["Available"] = availableList;
            ViewData["Category"] = categoryList;
            return View(property);
        }

        //
        // POST: /Property/Edit/5
        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult Edit(string id, FormCollection collection)
        {
            try
            {
                Property property = adminRepository.GetElementByID(id);
                UpdateModel<Property>(property);
                adminRepository.Save();
                return RedirectToAction("List", "Property", new { id = property.ID });
            }
            catch
            {
                adminRepository.CreateViewDataForDropLists(out categoryList, out availableList);
                ViewData["Available"] = availableList;
                ViewData["Category"] = categoryList;
                return View();
            }
        }


        // GET: /Property/Delete/5
        [Authorize(Roles = "Admin")]
        public ActionResult Delete(string id)
        {
            Property property = adminRepository.GetElementByID(id);
            if (property == null)
                throw new ArgumentException("未找到对应的物品");
            return View(property);
        }

        //Todo:IMPORTANT:删除时验证数据库数据完整性，检查各个表之间的关系
        // POST: /Property/Delete/5
        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult Delete(string id, FormCollection collection)
        {
            try
            {
                Property propertyToDelete = adminRepository.GetElementByID(id);
                adminRepository.Delete(propertyToDelete);
                adminRepository.Save();
                return RedirectToAction("ListAll","Property");
            }
            catch
            {
                return View();
            }
        }

        //Todo(DLJ):此处应该可以用Ajax实现？
        // GET: /Property/ApproveApply/{BorrowLogID}
        [Authorize(Roles = "Admin")]
        public ActionResult ApproveApply(string id)
        {
            Repository<BorrowLog> borrowLogRepository = new Repository<BorrowLog>(new DBModelDataContext());           //建立BorrowLog的数据模型类的实例
            if (borrowLogRepository.IsExist(id))
            {
                BorrowLog log = borrowLogRepository.GetElementByID(id);
                if (log.Property.Status == true)
                    throw new Exceptions.PermissionDeniedException("物品已经被借出，无法通过此借出申请");         //IMPORTANT:此处的判断很重要！可以允许多人申请借出同一个物品，但是只能审核通过一个
                else
                {
                    adminRepository.ApproveBorrowApply(log, User.Identity.Name);
                    adminRepository.Save();
                    borrowLogRepository.Save();
                    return RedirectToAction("PendingApplies");
                }
            }
            else
            {
                throw new ArgumentException("未找到对应的借出申请");
            }

        }

        [Authorize(Roles = "Admin")]
        public ActionResult PendingApplies()
        {
            Repository<BorrowLog> borrowLogRepository = new Repository<BorrowLog>(new DBModelDataContext());
            List<BorrowLog> borrowLogList = borrowLogRepository.GetAll(c => c.IsApproved == false).ToList();
            if (borrowLogList.Count > 0)
            {
                List<ViewModels.GetPendingPropertyBorrowApply> viewModelList = new List<ViewModels.GetPendingPropertyBorrowApply>();
                Models.AccountMembershipService accountService = new AccountMembershipService();
                foreach (BorrowLog log in borrowLogList)
                {
                    viewModelList.Add(new ViewModels.GetPendingPropertyBorrowApply { ApplyTime = log.ApplyTime, BorrowerName = log.UserName, ID = log.PropertyID, Name = log.Property.Name, BorrowerInfo = accountService.GetUserInfo(log.UserName), BorrowLogID = log.ID });
                }
                return View(viewModelList);
            }
            else
            {
                return View(new List<ViewModels.GetPendingPropertyBorrowApply>());
            }
        }

        [Authorize(Roles = "Admin")]
        public ActionResult DenyApply(string id)
        {
            Repository<BorrowLog> borrowLogRepository = new Repository<BorrowLog>(new DBModelDataContext());
            List<BorrowLog> logList = borrowLogRepository.GetAll(c => c.ID.ToString() == id).ToList();
            if (logList.Count <= 0)
                throw new ArgumentException("未找到对应的借出申请");
            else
            {
                BorrowLog log = logList.Single();
                if (log.IsApproved == true)
                    throw new Exceptions.PermissionDeniedException("该申请已经被审核通过，您无法拒绝已通过的申请");
                else
                {
                    borrowLogRepository.Delete(log);
                    borrowLogRepository.Save();
                    return RedirectToAction("PendingApplies");
                }
            }
        }
    }
}
